package Exercise2;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPTest2 {
    @Test
    public void client() {
        Socket socket = null;
        OutputStream os = null;
        FileInputStream fis = null;
        try {
            InetAddress inet = InetAddress.getByName("127.0.0.1");
            socket = new Socket(inet, 8090);
            os = socket.getOutputStream();
            fis = new FileInputStream("微信图片_20220908122927.jpg");
            byte buffer[] = new byte[20];
            int len;
            while ((len=fis.read(buffer))!=-1)
            {
                os.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(socket!=null)
            {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os!=null)
            {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis!=null)
            {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void service() {
        ServerSocket socket = null;
        Socket accept = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            socket = new ServerSocket(8090);
            accept = socket.accept();
            is = accept.getInputStream();
            fos = new FileOutputStream("微信图片_20220908122927service1.jpg");
            byte buffer[] = new byte[20];
            int len;
            while ((len=is.read(buffer))!=-1)
            {
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(socket!=null)
            {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(accept!=null)
            {
                try {
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is!=null)
            {

                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos!=null)
            {

                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
